<?php
namespace field\variable;

use field\variable\BaseField;
use Utils\AjaxMsg;

class StringField extends BaseField {
    public $name;
    public $description;
    public $extra;
    public $maxlength = 255;
    public $value;

    public function __construct($name, $description, $extra){
        $this->name = $name;
        $this->description = $description;
        $this->extra = $extra;

        if(isset($extra['maxlength'])){
            $this->maxlength = $extra['maxlength'];
        }
    }

    /**
     * 转换输入数据
     */
    public function parse($data){
        if(strlen($data) > $this->maxlength){
            $msg = new AjaxMsg();
            $msg->addMsg('error', 'ERR::STRING_TOO_LONG', '错误', '字符串过长');
            return $msg;
        } else {
            $this->value = $data;
            return $this->value;
        }
    }

    /**
     * 转为string输出
     */
    public function toString(){
        return $this->value;
    }

    /**
     * 转为数据库格式
     */
    public function toDatabase(){
        return $this->value;
    }

    /**
     * 获取数据库的数据类型
     */
    public function getDatabaseType(){
        return 'varchar(' . $this->maxlength . ')';
    }

    public static function getBaseName(){
        return '字符串';
    }

    /**
     * 获取在后台配置时显示的附加数据html
     */
    public static function getExtraConfigHtml(){
        return '<div class="form-group"><label>最大长度：</label><input type="text" class="form-control" data-id="maxlength"></input></div>';
    }

    /**
     * 解析传入的附加参数
     */
    public static function parseExtraConfigParam($params){
        $finalParams = [];
        if(isset($params['maxlength'])){
            $finalParams['maxlength'] = intval($params['maxlength']);
        }
        return $finalParams;
    }
}